<?php

namespace app\common\model\logic;

class ConfigModel
{
    public function __construct()
    {
        $this->curModel = model('dao.config');
    }

    public function getListPage($data)
    {
        $page = getPageData(); //获取分页数据
        $where[] = ['id', '>', 0];
        if (isset($data['keyword']) && !empty($data['keyword'])) {
            $where[] = ['tag', 'like', '%'.$data['keyword'].'%'];
        }
        $list = $this->curModel->where($where)->limit($page['start'], $page['limit'])->order('id desc')->all();
        if ($list->isEmpty()) {
            exception(lang('GET_ERROR'), 0, 'app\\common\\exception\\DataEmptyException');
        } else {
            $data['total'] = $this->curModel->where($where)->count();
            $data['list'] = $list;

            return $data;
        }
    }

    //保存添加
    public function saveAdd($data)
    {
        $data['status'] = 1;

        return $this->curModel->allowField(true)->isUpdate(false)->save($data);
    }

    //保存编辑
    public function saveEdit($data)
    {
        $this->getRow($data);

        return $this->curModel->allowField(true)->isUpdate(true)->save($data);
    }

    //保存删除
    public function saveDel($data)
    {
        $where[] = ['id', '=', $data['id']];

        $line = $this->getLine($where);
        if (empty($line)) {
            exception(lang('DEL_ERROR'), 0, 'app\\common\\exception\\LogicException');
        }

        $result = $this->curModel->destroy($data['id']);
        if ($result !== false) {
            return $result;
        } else {
            exception(lang('DEL_ERROR'), 0, 'app\\common\\exception\\LogicException');
        }
    }

    //获取单行
    public function getRow($data)
    {
        $where[] = ['id', '=', $data['id']];

        $line = $this->getLine($where);
        if (empty($line)) {
            exception(lang('GET_ERROR'), 0, 'app\\common\\exception\\DataEmptyException');
        } else {
            return $line;
        }
    }

    //根据条件获取单行
    public function getLine($where)
    {
        return  $this->curModel->where($where)->find();
    }

    //获取指定分类配置
    public function getCategoryList($data)
    {
        $where[] = ['category', '=', $data['category']];
        $where[] = ['status', '=', 1];
        $configList = $this->curModel->where($where)->field('id,category,name,tag,value,value_type,describe,status')->order('sort desc,id asc')->all();
        if ($configList->isEmpty()) {
            exception('没有设置配置项', 0, 'app\\common\\exception\\DataEmptyException');
        } else {
            return $configList;
        }
    }

    public function saveCategoryConfig()
    {
        $dataList = input('config_list');

        return $this->curModel->saveAll($dataList);
    }

    public function getTagConfig($data)
    {
        $where[] = ['tag', '=', $data['tag']];
        $line = $this->getLine($where);

        return $line['value'];
    }
}
